package cn.enjoy.rocketmq.listener;

import cn.enjoy.rocketmq.constant.MqTagConstant;
import com.aliyun.openservices.ons.api.Action;
import com.aliyun.openservices.ons.api.ConsumeContext;
import com.aliyun.openservices.ons.api.Message;
import com.aliyun.openservices.ons.api.MessageListener;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @author K
 * @date 2021-10-31 16:52
 */
@Component
public class MqListener implements MessageListener {
    @Autowired
    private ObjectMapper objectMapper;


    @SneakyThrows
    @Override
    public Action consume(Message message, ConsumeContext consumeContext) {
        boolean flag = false;
        try {
            switch (message.getTag()) {
                case MqTagConstant.HELLO:
                    String msg = objectMapper.readValue(message.getBody(), String.class);
                    System.out.println(msg);
                    flag = true;
                    break;
                default:
                    return Action.ReconsumeLater;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return Action.ReconsumeLater;
        }
        return flag ? Action.CommitMessage : Action.ReconsumeLater;
    }

}